<?php
require_once dirname(__FILE__) . '/metadata.php';
require_once dirname(__FILE__) . '/DbUtils.class.php';
require_once dirname(__FILE__) . '/includes/MiscUtils.class.php';

settle();

function settle() {
  $myPdo = DbUtils::createPdoInst();
  $tmps = DbUtils::get($myPdo, TABLE_NAME_PREFIX_MODULE . 'data_transaction', NULL, NULL, NULL, NULL, NULL, NULL)->d;
  if (count($tmps) > 0) {
    foreach ($tmps as $tmp) {
      $cond_vals = new stdClass();
      $cond_vals->c = 't.transaction_track_id = :v1';
      $cond_vals->v = array(':v1' => $tmp->track_id);
      $settles = DbUtils::get($myPdo, TABLE_NAME_PREFIX_MODULE . 'data_transaction_settle', $cond_vals, NULL, NULL, NULL, NULL, NULL)->d;
      if (count($settles) > 0) {
      	$obj = $settles[0];
        $obj->transaction_track_id = $tmp->track_id;
        $obj->amount = $tmp->sell_amount;
        $obj->method = $tmp->get_method;
        DbUtils::update($myPdo, TABLE_NAME_PREFIX_MODULE . 'data_transaction_settle', $obj);
      } else {
	      $obj = new stdClass();
	      $obj->track_id = MiscUtils::unique();
	      $obj->transaction_track_id = $tmp->track_id;
	      $obj->amount = $tmp->sell_amount;
	      $obj->method = $tmp->get_method;
	      DbUtils::add($myPdo, TABLE_NAME_PREFIX_MODULE . 'data_transaction_settle', $obj);
      }
      
      if ($tmp->fee_method == 'Deduct from settlement') {
        $tmp->fee_settle_track_id = $obj->track_id;
      }
      DbUtils::update($myPdo, TABLE_NAME_PREFIX_MODULE . 'data_transaction', $tmp);
    }
    echo 'Successfully';
  }
}
?>